﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Assembly
{
    public partial class frm_Add_F4ExportTroubles : Form
    {
        private List<string> serialList;
        private List<string> selectedSerial;        
        public frm_Add_F4ExportTroubles()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            serialList = new List<string>();
            selectedSerial = new List<string>();            
            this.addDate.EditValue = DateTime.Now.Date;
            getOrderNoList();
            this.orderNo.Properties.AutoComplete = true;
            getCheckerList();
            this.staffID.Properties.AutoComplete = true;
        }
        
        ////////////////////////////////////////////////
        /// Load Order No list to form
        ////////////////////////////////////////////////
        private void getOrderNoList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT TimePlanNo, CompID"
                    + " FROM [231_TimePlan] WHERE FinishedDate IS NOT NULL ORDER BY TimePlanNo";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {                    
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["TimePlanNo"].ToString();                    
                    item.Value = dataReader["TimePlanNo"].ToString();
                    this.orderNo.Properties.Items.Add(item);

                    ComboboxItem item2 = new ComboboxItem();
                    item2.Text = dataReader["CompID"].ToString();
                    item2.Value = dataReader["CompID"].ToString();
                    this.partNo.Properties.Items.Add(item2);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get OrderNo list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Staff list to Checker combobox
        ////////////////////////////////////////////////
        private void getCheckerList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT StaffID, StaffName"
                    + " FROM [222_Staff] WHERE StopDate IS NULL ORDER BY StaffName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["StaffName"].ToString() + " | " + dataReader["StaffID"].ToString();
                    item.Value = dataReader["StaffID"].ToString();
                    this.staffID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch //(Exception ex)
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                //MessageBox.Show(ex.Message);
                MessageBox.Show("Cannot get Checker list");
            }
        } 

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }        
        
        ///////////////////////////
        /// When Click Add Button
        ///////////////////////////        
        private void buttonAdd_Click(object sender, EventArgs e)
        {
            string error = null;
            DateTime inputdate;
            string order = null;
            string serial = null;
            int trouble_quantity = 0;
            int total_quantity = 0;
            string checker = null;
            string trouble = null;
            string reason = null;
            string remark = null;

            ComboboxItem item = new ComboboxItem();

            if (!DateTime.TryParse(this.addDate.DateTime.Date.ToString(), out inputdate))
            {
                error = "Please select Date";
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.orderNo.SelectedIndex < 0)
                {
                    error = "Please Select Order No.";
                }
                else
                {
                    item = (ComboboxItem)this.orderNo.SelectedItem;
                    order = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (!Int32.TryParse(this.quantityValue.Text, out total_quantity))
                {
                    error = "Invalid Total Quantity";
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                trouble_quantity = selectedSerial.Count;               
            }

            if (string.IsNullOrEmpty(error))
            {
                if (trouble_quantity <= 0)
                {
                    error = "Troube quantity must be greater than 0";
                }
                else
                {
                    if (trouble_quantity > total_quantity)
                    {
                        error = "Trouble quantity cannot be greater than Total quantity";
                    }
                    else
                    {
                        for (int i = 0; i < selectedSerial.Count; i++)
                        {
                            if (i == 0)
                            {
                                serial += selectedSerial[i].ToString();
                            }
                            else
                            {
                                serial += "," + selectedSerial[i].ToString();
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(error))
            {
                if (this.staffID.SelectedIndex < 0)
                {
                    error = "Please Select Checker.";
                }
                else
                {
                    item = (ComboboxItem)this.staffID.SelectedItem;
                    checker = item.Value.ToString();
                }
            }

            if (string.IsNullOrEmpty(error))
            {                
                trouble = this.troubleContent.Text;
                reason = this.troubleReason.Text;
                remark = this.noteText.Text;
                try
                {
                    myConnection.Open();
                    string sql = "INSERT INTO [231_F4Troubles] (Date, TimePlanNo, SerialNo, Quantity, Checker,"
                        + " F4TroubleContent, Reason, Remark, Type)"
                        + " VALUES (@dateinput, '" + order + "', '" + serial + "', " + trouble_quantity + ", '" + checker + "'," 
                        + " '" + trouble + "', '" + reason + "', '" + remark + "', 1)";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@dateinput", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("F4 Export Trouble added success.");
                }
                catch //(Exception ex)
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    //MessageBox.Show(ex.Message);
                    MessageBox.Show("Cannot add F4 Export Trouble. Please try again.");
                }                 
            }
            else
            {
                MessageBox.Show(error);
            }
        }

        /////////////////////////////////////
        /// When Change Order No
        /////////////////////////////////////
        private void orderNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.orderNo.SelectedIndex > -1)
            {
                this.partNo.SelectedIndex = this.orderNo.SelectedIndex;
                getSerialList();                
                this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();                
            }
        }
       
        /////////////////////////////////////////////////
        /// Create Serial No List with selected Order No
        /////////////////////////////////////////////////
        private void getSerialList()
        {
            serialList.Clear();
            serialNo.DataSource = null;
            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;
            this.serialNo.Enabled = true;
            this.selectedSerialNo.Enabled = true;
            this.buttonSelectAll.Enabled = true;
            this.buttonSelect.Enabled = true;
            this.buttonDeselect.Enabled = true;
            this.buttonDeselectAll.Enabled = true;
            this.troubleQty.Enabled = false;
            
            ComboboxItem order = (ComboboxItem)this.orderNo.SelectedItem;
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SerialNo FROM [231_RobotOrderDetail] WHERE OrderNo='" + order.Value + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    serialList.Add(dataReader["SerialNo"].ToString());                    
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();

                serialNo.DataSource = serialList;
                quantityValue.Text = serialList.Count.ToString();
                troubleQty.Text = "0";
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
            }            
        }

        ////////////////////////////
        /// Select All Serial
        ////////////////////////////
        private void buttonSelectAll_Click(object sender, EventArgs e)
        {            
            foreach (string value in serialList)
            {
                selectedSerial.Add(value);
            }
            //selectedSerial = serialList;
            selectedSerialNo.DataSource = null;
            selectedSerial.Sort();
            selectedSerialNo.DataSource = selectedSerial;

            serialList.Clear();
            serialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }

        /////////////////////////////////////
        /// Deselect all serial
        ////////////////////////////////////
        private void buttonDeselectAll_Click(object sender, EventArgs e)
        {
            foreach (string value in selectedSerial)
            {
                serialList.Add(value);
            }
            //selectedSerial = serialList;
            serialNo.DataSource = null;
            serialList.Sort();
            serialNo.DataSource = serialList;

            selectedSerial.Clear();
            selectedSerialNo.DataSource = null;

            //this.quantityValue.Text = this.serialList.Count.ToString();
            this.troubleQty.Text = this.selectedSerial.Count.ToString();
        }
        
        /////////////////////////////
        /// Select some serial
        /////////////////////////////
        
        private void buttonSelect_Click(object sender, EventArgs e)
        {
            if (serialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < serialNo.SelectedItems.Count; i++)
                {
                    selectedSerial.Add(serialNo.SelectedItems[i].ToString());                    
                }
                for (int i = serialNo.SelectedItems.Count - 1; i >= 0 ; i--)
                {                    
                    serialList.Remove(serialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }            
        }

        /////////////////////////////
        /// Deselect some serial
        /////////////////////////////
        private void buttonDeselect_Click(object sender, EventArgs e)
        {
            if (selectedSerialNo.SelectedItems.Count > 0)
            {
                for (int i = 0; i < selectedSerialNo.SelectedItems.Count; i++)
                {
                    serialList.Add(selectedSerialNo.SelectedItems[i].ToString());
                }
                for (int i = selectedSerialNo.SelectedItems.Count - 1; i >= 0; i--)
                {
                    selectedSerial.Remove(selectedSerialNo.SelectedItems[i].ToString());
                }
                serialNo.DataSource = null;
                serialList.Sort();
                serialNo.DataSource = serialList;
                selectedSerialNo.DataSource = null;
                selectedSerial.Sort();
                selectedSerialNo.DataSource = selectedSerial;

                //this.quantityValue.Text = this.serialList.Count.ToString();
                this.troubleQty.Text = this.selectedSerial.Count.ToString();
            }
        }
    }
}
